package com.gexiaobao.pigeon.ui.fragment.match

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentSignUpDetailBinding
import com.gexiaobao.pigeon.ui.adapter.SignUpPigeonDetailAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogPageTurning
import com.gexiaobao.pigeon.ui.race.RaceViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import kotlin.math.ceil

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 15:07
 * @Describe    : 集鸽详情
 */
class FragmentSignUpDetail : BaseFragment<RaceViewModel, FragmentSignUpDetailBinding>() {

    private var mPassId = ""
    private var memberCode = ""
    private var searchNameStr = ""
    private val mAdapter: SignUpPigeonDetailAdapter by lazy { SignUpPigeonDetailAdapter(arrayListOf()) }

    private var mPageNo: Int = 1
    private var mPageTotal = 0
    private var mTotalNum = 0

    override fun initView(savedInstanceState: Bundle?) {
        val title = arguments?.getString("title")
        memberCode = arguments?.getString("memberCode").toString()
        searchNameStr = memberCode
        if (!title.isNullOrBlank()) {
            mDatabind.includeBar.toolbar.initClose(title) {
                nav().navigateUp()
            }
        }
        mDatabind.includeSearchEt.etSearch.setText(memberCode)
    }

    private fun searchData() {
        hideSoftKeyboard(activity)
        searchNameStr = mDatabind.includeSearchEt.etSearch.text.toString()
        when {
            searchNameStr.isEmpty() -> showMessage("请输入搜索内容")
            else -> {
                showLoading(getString(R.string.loading))
                mViewModel.getGatherListForHand(mPassId, searchNameStr, mPageNo)
            }
        }
    }

    override fun initData() {
        super.initData()

        mDatabind.includeSearchEt.etSearch.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH ->
                    searchData()

                else -> {}
            }
            false
        }

        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter)
            .addItemDecoration(SpaceItemDecoration(0, Util.dp2px(context, 0f)))

        mDatabind.layoutList.swipeRefreshLayout.init {
            mViewModel.getGatherListForHand(mPassId, searchNameStr, mPageNo)
        }

        mAdapter.addChildClickViewIds(R.id.tv_item_sign_up_pigeon_foster_name)
        mAdapter.addChildClickViewIds(R.id.tv_item_sign_up_pigeon_member_num)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tv_item_sign_up_pigeon_foster_name -> {
                    mPageNo = 1
                    searchNameStr = mAdapter.data[position].fosterName
                    mDatabind.includeSearchEt.etSearch.setText(searchNameStr)
                    mDatabind.includeSearchEt.etSearch.setSelection(searchNameStr.length)
                    onRefresh(mPageNo)
                    RxToast.showToast(searchNameStr)
                }

                R.id.tv_item_sign_up_pigeon_member_num -> {
                    mPageNo = 1
                    searchNameStr = mAdapter.data[position].memberNum
                    mDatabind.includeSearchEt.etSearch.setText(searchNameStr)
                    mDatabind.includeSearchEt.etSearch.setSelection(searchNameStr.length)
                    onRefresh(mPageNo)
                    RxToast.showToast(searchNameStr)
                }
            }
        }
    }

    private fun onRefresh(pageNo: Int) {
        showLoading(getString(R.string.loading))
        mViewModel.getGatherListForHand(mPassId, searchNameStr, pageNo)
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        mPageNo = 1
        mPassId = arguments?.getInt("id").toString()
        onRefresh(mPageNo)
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 集鸽详情 */
        mViewModel.gatherDetailResponse.observe(viewLifecycleOwner) {
            if (mDatabind.layoutList.swipeRefreshLayout.isRefreshing) {
                mDatabind.layoutList.swipeRefreshLayout.isRefreshing = false
            }
            mTotalNum = it.total
            mAdapter.setTotal(mTotalNum, mPageNo)
            mAdapter.setList(it.data)
            mAdapter.notifyDataSetChanged()
            mPageTotal = ceil(SettingUtil.div(mTotalNum.toDouble(), 50.00, 2)).toInt()//取整
            mDatabind.organizeSearchNumber.text = "检索到赛鸽" + it.total + "羽" + "   共: " + mPageTotal + "页"
            mDatabind.layoutList.swipeRecyclerView.scrollToPosition(0)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.collectionResultPageAll,
            mDatabind.collectionResultPageMine,
            mDatabind.includeSearchEt.etSearchTv,
            mDatabind.includePage.tvFirstPage,
            mDatabind.includePage.tvPageUp,
            mDatabind.includePage.tvLastPage,
            mDatabind.includePage.tvThrough,
            mDatabind.includePage.tvNextPage,
        ) {
            when (it) {
                mDatabind.includePage.tvThrough -> showDialogPageTurning()
                mDatabind.includePage.tvLastPage -> {
                    mPageNo = mPageTotal
                    onRefresh(mPageNo)
                    mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includePage.tvNextPage -> {
                    if (mPageNo == mPageTotal) {
                        RxToast.warning("当前已经是最后一页")
                        return@setOnclickNoRepeat
                    }
                    mPageNo++
                    onRefresh(mPageNo)
                    mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includePage.tvPageUp -> {
                    if (mPageNo == 1) {
                        RxToast.warning("当前已经是第一页")
                        return@setOnclickNoRepeat
                    }
                    mPageNo--
                    onRefresh(mPageNo)
                    mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.includePage.tvFirstPage -> {
                    mPageNo = 1
                    onRefresh(mPageNo)
                    mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
                }

                mDatabind.collectionResultPageAll -> {
                    mPageNo = 1
                    searchNameStr = ""
                    mDatabind.includeSearchEt.etSearch.setText("")
                    onRefresh(mPageNo)
                }

                mDatabind.collectionResultPageMine -> {
                    mPageNo = 1
                    searchNameStr = memberCode
                    mDatabind.includeSearchEt.etSearch.setText(searchNameStr)
                    mDatabind.includeSearchEt.etSearch.setSelection(searchNameStr.length)
                    onRefresh(mPageNo)
                }

                mDatabind.includeSearchEt.etSearchTv -> {
                    mPageNo = 1
                    if (mDatabind.includeSearchEt.etSearch.text?.isEmpty() == true) {
                        RxToast.showToast("请输入查询内容")
                        return@setOnclickNoRepeat
                    }
                    searchNameStr = mDatabind.includeSearchEt.etSearch.text.toString()
                    onRefresh(mPageNo)
                }
            }
        }
    }

    private fun showDialogPageTurning() {
        var pageNumber: Int
        val dialog = RxDialogPageTurning(context)
        dialog.setTitle("选择要查看的页码\n共： $mPageTotal  页")
        dialog.setPlusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (pageNumber > mPageTotal) {
                RxToast.warning("您的输入已超出总页码")
                return@setPlusListener
            }
            if (pageNumber == mPageTotal) {
                RxToast.warning("当前已经是最后一页")
                return@setPlusListener
            }
            pageNumber++
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setMinusListener {
            pageNumber = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }

            if (pageNumber == 1) {
                RxToast.warning("当前已经是第一页")
                return@setMinusListener
            }
            pageNumber--
            dialog.setCurrentPage(pageNumber.toString())
        }
        dialog.setSureListener {
            mPageNo = if (dialog.getCurrentPage().isEmpty()) {
                1
            } else {
                dialog.getCurrentPage().toInt()
            }
            if (mPageNo > mPageTotal) {
                RxToast.warning("您的输入已超出总页码")
                return@setSureListener
            }
            mDatabind.includePage.tvPageNumber.text = mPageNo.toString()
            onRefresh(mPageNo)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }
}